package servlet;

import dao.ArticleDao;
import dao.CollectionDao;
import dao.daoimpl.ArticleDaoImpl;
import dao.daoimpl.CollectionDaoImpl;
import bean.Collection;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
/*删除博客服务器*/
@WebServlet(name="DeleteCollectionServlet",urlPatterns = "/DeleteCollectionServlet")
public class DeleteCollectionServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        int articleId=Integer.parseInt(request.getParameter("deleteCollectionArticleId"));/*博客id*/
        CollectionDao collectionDao=new CollectionDaoImpl();/*收藏接口的实现类*/
        ArticleDao articleDao=new ArticleDaoImpl();
        User user=(User)request.getSession().getAttribute("user");/*获取用户*/
        ArrayList<Collection>collections=(ArrayList<Collection>)request.getSession().getAttribute("userCollected");/*获取收藏集合*/
        int id=0;
        for(int i=0;i<collections.size();i++){
            if(collections.get(i).getArticleId()==articleId){
                id=collections.get(i).getId();
                break;
            }
        }
        if(collectionDao.deleteCollection(id)){/*进行删除收藏操作*/
            System.out.println("删除收藏成功");
            try {
                request.getSession().setAttribute("userCollections",articleDao.getCollectedArticles(user));/*返回用户收藏集合*/
                request.getSession().setAttribute("userCollected",collectionDao.getCollections(user));
                request.getSession().setAttribute("allPage",articleDao.getPage(user));
            } catch (SQLException sqlException) {
                sqlException.printStackTrace();
            }
        }else{
            System.out.println("删除收藏失败");
        }
    }
}
